import datetime
import json
from time import sleep

import allure

from common.commin.commin import read_ini, json_to_yaml
from common.log.log import log
from common.request.request_api import RequestHandler
from common.yaml.read_yaml import read_yaml_data
from config.conf import BASE_DIR

# 环境地址
# url_yg = read_ini(BASE_DIR + '/config_yg.ini')['host']['url']


class AppletsApi:
    """
    花王云购+ api
    """

    def __init__(self, url):
        # 环境地址
        self.env_url = url

    @allure.step('api接口——个人中心查看我的订单列表')
    def api_applets_my_order(self, token):
        """
        api接口——个人中心查看我的订单列表
        token：
        """
        try:
            log.info('api接口——个人中心查看我的订单列表')
            req = RequestHandler(token, 'yc')
            get_url = self.env_url + f'/jinhua/api/front/order/list?type=5&page=1&limit=20'

            response = req.visit('get', get_url, )
            return response.text
        except Exception as e:
            log.error(f'api接口——个人中心查看我的订单列表出现异常为：{e}')
            raise e

    @allure.step('api接口——分享')
    def api_applets_front_share(self, token):
        """
        api接口——分享
        """
        try:
            log.info('api接口——分享')
            req = RequestHandler(token, 'yc')
            get_url = self.env_url + f'/jinhua/api/front/share'
            response = req.visit('get', get_url, )
            return response.text
        except Exception as e:
            log.error(f'api接口——分享：{e}')
            raise e

    @allure.step('api接口——搜索')
    def api_applets_front_search(self, token, keyword):
        """
        api接口——搜索
        """
        try:
            log.info('api接口——搜索')
            req = RequestHandler(token, 'yc')
            get_url = self.env_url + f'/jinhua/api/front/products?keyword={keyword}&page=1&limit=8'

            response = req.visit('get', get_url, )
            return response.text
        except Exception as e:
            log.error(f'api接口——搜索：{e}')
            raise e

    @allure.step('api接口——商品详情页')
    def api_applets_product_detail(self, token, product_id):
        """
        api接口——商品详情页
        token：鉴权
        product_id：商品id
        """
        try:
            log.info('api接口——商品详情页')
            req = RequestHandler(token, 'yc')
            get_url = self.env_url + f'/jinhua/api/front/product/detail/{product_id}?type=normal'

            response = req.visit('get', get_url, )
            return response.text
        except Exception as e:
            log.error(f'api接口——商品详情页：{e}')
            raise e

    @allure.step('api接口——切换分类')
    def api_applets_index_product(self, token):
        """
        api接口——切换分类
        """
        try:
            log.info('api接口——切换分类')
            req = RequestHandler(token, 'yc')
            get_url = self.env_url + f'/jinhua/api/front/index/product/4?page=1&limit=10'

            response = req.visit('get', get_url, )
            return response.text
        except Exception as e:
            log.error(f'api接口——切换分类：{e}')
            raise e

    @allure.step('api接口——用户我的')
    def api_applets_front_user(self, token):
        """
        api接口——用户我的
        """
        try:
            log.info('api接口——用户我的')
            req = RequestHandler(token, 'yc')
            get_url = self.env_url + f'/jinhua/api/front/user'

            response = req.visit('get', get_url, )
            return response.text
        except Exception as e:
            log.error(f'api接口——用户我的：{e}')
            raise e

    @allure.step('api接口——申请提现')
    def api_applets_front_contract_extract(self, token, price):
        """
        api接口——申请提现
        token: 接口token
        price: 申请提现金额
        """
        try:
            log.info('api接口——申请提现')
            req = RequestHandler(token, 'yc')
            json = {
                "price": price
            }
            get_url = self.env_url + f'/jinhua/api/front/contract/extract'
            response = req.visit('post', get_url, json=json)
            return response.text
        except Exception as e:
            log.error(f'api接口——申请提现：{e}')
            raise e

    @allure.step('api接口——预下单')
    def api_applets_front_order_pre(self, token, preOrderType, attrValueId, productId, productNum, isVip):
        """
        api接口——预下单
        token
        preOrderType：预下单类型（“shoppingCart”：购物车下单，“buyNow”：立即购买，”again“： 再次购买，”video“: 视频号商品下单）
        attrValueId：商品规格属性id（立即购买、活动购买必填）
        productId：商品id（立即购买必填）
        productNum：商品数量（立即购买、活动购买必填）
        isVip：是否会员礼包商品
        """
        try:
            log.info('api接口——预下单')
            req = RequestHandler(token, 'yc')
            json = {
                "preOrderType": preOrderType,
                "orderDetails": [{
                    "attrValueId": attrValueId,
                    "productId": productId,
                    "productNum": productNum,
                    "isVip": isVip
                }]
            }
            get_url = self.env_url + f'/jinhua/api/front/order/pre/order'
            response = req.visit('post', get_url, json=json)
            log.info(response.text)
            return response.text
        except Exception as e:
            log.error(f'api接口——预下单：{e}')
            raise e

    @allure.step('api接口——加载预下单')
    def api_applets_front_order_load_pre(self, token, preOrderNo):
        """
        api接口——加载预下单
        Args:
            token:
            preOrderNo:预下单id

        Returns:

        """
        try:
            log.info('api接口——加载预下单')
            req = RequestHandler(token, 'yc')
            get_url = self.env_url + f'/jinhua/api/front/order/load/pre/{preOrderNo}'
            response = req.visit('get', get_url, )
            log.info(response.text)
            return response.text
        except Exception as e:
            log.error(f'api接口——加载预下单：{e}')
            raise e

    @allure.step('api接口——当前订单可用优惠券')
    def api_applets_front_coupons_order(self, token, preOrderNo):
        """
        api接口——当前订单可用优惠券
        Args:
            token:
            preOrderNo:

        Returns:

        """
        try:
            log.info('api接口——当前订单可用优惠券')
            req = RequestHandler(token, 'yc')
            get_url = self.env_url + f'/jinhua/api/front/coupons/order/{preOrderNo}'
            response = req.visit('get', get_url, )
            log.info(response.text)
            return response.text
        except Exception as e:
            log.error(f'api接口——当前订单可用优惠券：{e}')
            raise e

    @allure.step('api接口——获取商品信息，用于下单购买')
    def get_yaml_sp_info(self, applets_token):
        """
        获取商品信息相关信息，用于下单购买
        Args:
            applets_token:
        Returns:
            productId：商品iD
            attrValueId：商品规格属性ID
            stock：库存
            sales：销量

        """
        # 更新下单的商品信息到yaml（取瀑布流第一个商品进行下单购买）
        yaml_file = AppletsApi(self.env_url).update_product_detail_yaml(applets_token)
        data = read_yaml_data(yaml_file)
        productValue = data['data']['productValue']
        attrValues = list(productValue.keys())[0]  # 取第一个组合的规格值
        productId = data['data']['productValue'][attrValues]['productId']
        log.info(f'商品id为：{productId}')
        attrValueId = data['data']['productValue'][attrValues]['id']
        log.info(f"商品规格属性id为：{attrValueId}")
        stock = data['data']['productValue'][attrValues]['stock']
        log.info(f"商品规格属性的库存为：{stock}")
        sales = data['data']['productValue'][attrValues]['sales']
        log.info(f"商品规格属性的销量为：{sales}")
        giveIntegral = data['data']['productInfo']['giveIntegral']
        log.info(f"商品配置的赠送积分为：{giveIntegral}")
        price = data['data']['productValue'][attrValues]['price']
        log.info(f"商品售价为：{price}")

        return productId, attrValueId, stock, sales, giveIntegral, price

    @allure.step('api接口——创建订单')
    def api_applets_front_order_create(self, token, preOrderNo):
        """
        api接口——创建订单

        "realName": 真实姓名
        "phone": 手机号码
        "addressId": 收货地址id
        "couponId":  优惠券编号
        "payType":  支付类型:weixin-微信支付，yue-余额支付
        "useIntegral":  是否使用积分
        "preOrderNo": 预下单订单号
        "mark": 订单备注
        "storeId": 自提点id
        "shippingType": 快递类型: 1-快递配送，2-到店自提
        "payChannel": 支付渠道:weixinh5-微信H5支付，public-公众号支付，routine-小程序支付，weixinAppIos-微信appios支付，weixinAppAndroid-微信app安卓支付
        "isVip": 是否会员礼包订单
        "invoiceRequest": 订单发票数据

        """
        try:
            log.info('api接口——创建订单')
            req = RequestHandler(token, 'yc')
            json = {
                "realName": "",
                "phone": "",
                "addressId": 264,
                "couponId": 0,
                "payType": "yue",
                "useIntegral": False,
                "preOrderNo": preOrderNo,
                "mark": "",
                "storeId": 0,
                "shippingType": 1,
                "payChannel": "routine",
                "isVip": ""
            }
            get_url = self.env_url + f'/jinhua/api/front/order/create'
            response = req.visit('post', get_url, json=json)
            log.info(response.text)
            return response.text
        except Exception as e:
            log.error(f'api接口——创建订单：{e}')
            raise e

    @allure.step('api接口——订单支付')
    def api_applets_front_pay_payment(self, token, orderNo, payType='yue'):
        """
        api接口——订单支付

        orderNo：订单号
        "payChannel": 支付渠道:weixinh5-微信H5支付，public-公众号支付，routine-小程序支付，weixinAppIos-微信appios支付，weixinAppAndroid-微信app安卓支付
        "payType": 支付类型：weixin-微信支付，yue-余额支付，offline-线下支付，alipay-支付包支付
        "scene": 下单时小程序的场景值

        """
        try:
            log.info('api接口——订单支付')
            req = RequestHandler(token, 'yc')
            json = {
                "orderNo": orderNo,
                "payChannel": "routine",
                "payType": payType,
                "scene": 0
            }
            get_url = self.env_url + f'/jinhua/api/front/pay/payment'
            response = req.visit('post', get_url, json=json)
            log.info(response.text)
            return response.text
        except Exception as e:
            log.error(f'api接口——订单支付：{e}')
            raise e

    @allure.step('api接口——查看订单详情')
    def api_applets_front_order_detail_order(self, token, orderNo):
        """
        api接口——查看订单详情
        orderNo:订单号
        """
        try:
            log.info('api接口——查看订单详情')
            req = RequestHandler(token, 'yc')
            get_url = self.env_url + f'/jinhua/api/front/order/detail/{orderNo}'

            response = req.visit('get', get_url, )
            log.info(response.text)
            return response.text
        except Exception as e:
            log.error(f'api接口——查看订单详情：{e}')
            raise e

    @allure.step('api接口——确认收货')
    def api_applets_confirm_receipt(self, token, order_id):
        """
        api接口——查看订单详情
        Args:
            token:
            order_id:

        Returns:

        """
        try:
            log.info('api接口——确认收货')
            # 获取订单详情的id，用与确认收货
            res = self.api_applets_front_order_detail_order(token, order_id)
            id = json.loads(res)['data']['id']
            int_id = int(id)  # 要int型
            req = RequestHandler(token, 'yg')
            data_json = {'id': int_id}
            get_url = self.env_url + '/jinhua/api/front/order/take'
            response = req.visit('post', get_url, params=data_json)
            log.info(response.text)
            return response.text
        except Exception as e:
            log.error(f'api接口——确认收货：{e}')
            raise e

    @allure.step('api接口——获取待评价商品信息全部查询')
    def api_applets_order_all(self, token, order_id):
        """
        api接口——获取待评价商品信息全部查询
        orderNo:订单号
        """
        try:
            log.info('api接口——获取待评价商品信息全部查询')
            # 获取订单详情的id，用与确认收货
            res = self.api_applets_front_order_detail_order(token, order_id)
            id = json.loads(res)['data']['id']
            int_id = int(id)  # 要int型
            req = RequestHandler(token, 'yg')
            data_json = {
                'orderId': int_id
            }
            get_url = self.env_url + '/jinhua/api/front/order/product/all'
            response = req.visit('post', get_url, json=data_json)
            log.info(response.text)
            # 返回待评价商品信息全部查询的信息，样例如下：
            """
            {
                "code": 200,
                "message": "操作成功",
                "data": [{
                    "cartNum": 10,
                    "truePrice": "123.00",
                    "storeName": "花王卯年生肖酒(500ml)【自动化测试，勿动！】",
                    "image": "https://hwygtest.jinhua-global.com/jinhua/upload/image/content/2023/02/22/2a077a1f91f74d08958d35d644f155a7o5c5yvb45y.jpg",
                    "productId": 50,
                    "sku": "测试2"
                }]
            }
            """
            return json.loads(response.text)
        except Exception as e:
            log.error(f'api接口——获取待评价商品信息全部查询：{e}')
            raise e

    @allure.step('api接口——订单评价')
    def api_applets_order_evaluate(self, token, order_id):
        """
        api接口——订单评价
        Args:
            token:
            order_id:

        Returns:

        """
        try:
            log.info('api接口——订单评价')
            all_info = self.api_applets_order_all(token, order_id)
            data_json = {
                "infos": [{
                    "comment": "",
                    "pics": "",
                    "productId": all_info['data'][0]['productId'],
                    "productScore": 5,
                    "serviceScore": 5,
                    "sku": all_info['data'][0]['sku'],
                    "unique": ""
                }],
                "orderNo": order_id
            }
            req = RequestHandler(token, 'yg')
            get_url = self.env_url + '/jinhua/api/front/order/comment/all'
            response = req.visit('post', get_url, json=data_json)
            log.info(response.text)
            return response.text
        except Exception as e:
            log.error(f'api接口——订单评价：{e}')
            raise e

    @allure.step('api接口——首页商品瀑布流，return第一个商品id')
    def get_api_applets_index_product_id(self, token):
        """
        api接口——首页商品瀑布流，return第一个商品id
        """
        try:
            log.info('api接口——首页商品瀑布流，return第一个商品id')
            req = RequestHandler(token, 'yg')
            get_url = self.env_url + '/jinhua/api/front/index/product/1?page=1&limit=10'
            response = req.visit('get', get_url)
            log.info(response.text)
            return json.loads(response.text)['data']['list'][0]['id']
        except Exception as e:
            log.error(f'api接口——首页商品瀑布流：{e}')
            raise e

    @allure.step('api接口——更新商品信息的yaml')
    def update_product_detail_yaml(self, token):
        """
        api接口——更新商品信息的yaml
        """
        try:
            log.info('api接口——更新商品信息的yaml')
            sp_id = self.get_api_applets_index_product_id(token)
            yaml_file = BASE_DIR + '\data\product_detail.yaml'
            req = RequestHandler(token, 'yg')
            get_url = self.env_url + f'/jinhua/api/front/product/detail/{sp_id}?type=normal'
            response = req.visit('get', get_url)
            log.info(response.text)
            json_data = response.json()
            json_to_yaml(json_data, yaml_file)
            return yaml_file
        except Exception as e:
            log.error(f'api接口——更新商品信息的yaml：{e}')
            raise e

    @allure.step('创建订单并支付成功')
    def api_ordering_yg(self, token, preOrderType, attrValueId, productId, productNum, isVip):
        """
        创建订单并支付成功
        Args:
            token:小程序token
            preOrderType:购买类型
            attrValueId:规格id
            productId:商品id
            productNum:购买数
            isVip:是否vip

        Returns:
            orderNo：订单id
        """
        url_yg = read_ini(BASE_DIR + '/config_yg.ini')['host']['url']
        try:
            """
            ================测试环境才执行下单接口测试================
            """
            if 'test' in url_yg:
                # 预下单
                # 这里固定写死的商品名称为：花王卯年生肖酒(500ml)【自动化测试，勿动！】
                response = AppletsApi(url_yg).api_applets_front_order_pre(token, preOrderType, attrValueId, productId,
                                                                          productNum, isVip)
                preOrderNo = json.loads(response)['data']['preOrderNo']  # 预下单订单号
                # 加载预下单
                AppletsApi(url_yg).api_applets_front_order_load_pre(token, preOrderNo)
                # 当前订单可用优惠券
                AppletsApi(url_yg).api_applets_front_coupons_order(token, preOrderNo)
                # 创建订单
                create_result = AppletsApi(url_yg).api_applets_front_order_create(token, preOrderNo)
                orderNo = json.loads(create_result)['data']['orderNo']
                # 微信支付
                AppletsApi(url_yg).api_applets_front_pay_payment(token, orderNo, payType='weixin')
                """调试一下，复现积分重复加的bug"""
                sleep(3)
                # 余额支付
                AppletsApi(url_yg).api_applets_front_pay_payment(token, orderNo, payType='yue')
                return orderNo
            else:
                log.info('############# 生产环境暂不能下单 #############')
        except Exception as e:
            log.error(f'出现异常，异常为:{e}')
            raise e


if __name__ == '__main__':
    log.info('1')
